<template>
  <div class="customer-list">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>客户管理</h2>
      <p>客户信息查询与管理</p>
    </div>

    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="客户名称">
          <el-input
            v-model="searchForm.CustomerName"
            placeholder="请输入客户名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="客户类型">
          <el-select
            v-model="searchForm.CustomerType"
            placeholder="请选择客户类型"
            clearable
            style="width: 150px"
          >
            <el-option label="企业" value="企业" />
            <el-option label="个人" value="个人" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.State"
            placeholder="请选择状态"
            clearable
            style="width: 120px"
          >
            <el-option label="启用" :value="0" />
            <el-option label="禁用" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card class="action-card" shadow="never">
      <div class="action-buttons">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增客户
        </el-button>
        <el-button type="success" @click="handleExport" :loading="exportLoading">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
      </div>
    </el-card>

    <!-- 新增/编辑客户弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑客户' : '新增客户'"
      width="600px"
      :before-close="handleClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        label-position="right"
      >
        <el-form-item label="客户编码" prop="CustomerCode">
          <el-input
            v-model="form.CustomerCode"
            placeholder="系统自动生成"
            readonly
            disabled
          />
        </el-form-item>
        <el-form-item label="客户名称" prop="CustomerName">
          <el-input
            v-model="form.CustomerName"
            placeholder="请输入客户名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="客户类型" prop="CustomerType">
          <el-select
            v-model="form.CustomerType"
            placeholder="请选择客户类型"
            style="width: 100%"
          >
            <el-option label="企业" value="企业" />
            <el-option label="个人" value="个人" />
          </el-select>
        </el-form-item>
        <el-form-item label="联系人" prop="UserPeople">
          <el-input
            v-model="form.UserPeople"
            placeholder="请输入联系人"
            clearable
          />
        </el-form-item>
        <el-form-item label="联系电话" prop="Phone">
          <el-input
            v-model="form.Phone"
            placeholder="请输入联系电话"
            clearable
          />
        </el-form-item>
        <el-form-item label="状态" prop="State">
          <el-select
            v-model="form.State"
            placeholder="请选择状态"
            style="width: 100%"
          >
            <el-option label="启用" :value="0" />
            <el-option label="禁用" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="Desc">
          <el-input
            v-model="form.Desc"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <el-table :data="tableData" v-loading="loading" stripe border style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="customerCode" label="客户编码" width="120" />
        <el-table-column prop="customerName" label="客户名称" width="150" />
        <el-table-column prop="customerType" label="客户类型" width="100">
          <template #default="{ row }">
            <el-tag :type="row.customerType === '企业' ? 'primary' : 'success'">
              {{ row.customerType }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="userPeople" label="联系人" width="120" />
        <el-table-column prop="phone" label="联系电话" width="140" />
        <el-table-column prop="state" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.state === 0 ? 'success' : 'danger'">
              {{ row.state === 0 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="desc" label="备注" width="200" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.pageindex"
          v-model:page-size="pagination.pagesize"
          :page-sizes="[6, 10, 20, 50, 100]"
          :total="pagination.totalCount"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Search, Refresh, Plus, Download, Edit, Delete } from '@element-plus/icons-vue'
import { getReadClient, getWriteClient } from '@/Urls/AxiosHelper'

// 使用正确的客户端 - 客户相关操作都使用5154端口
const r3 = getReadClient(0)  // 5154端口用于读取
const w8 = getReadClient(0)  // 5154端口用于写入（客户相关操作）

// 接口类型定义
interface Customer {
  id: number
  customerCode: string
  customerName: string
  customerType: string
  userPeople: string
  state: number
  phone: string
  desc: string
  isDelete: boolean
}

interface ApiResponse {
  data: {
    totalCount: number
    totalPage: number
    data: Customer[]
  }
  code: number
  message: string
}

// 响应式数据
const loading = ref(false)
const tableData = ref<Customer[]>([])
const exportLoading = ref(false) // 导出加载状态

// 弹窗相关
const dialogVisible = ref(false)
const submitLoading = ref(false)
const formRef = ref<FormInstance>()
const isEdit = ref(false) // 是否为编辑模式
const currentEditId = ref<number | null>(null) // 当前编辑的客户ID

// 新增表单 - 匹配后端字段名
const form = reactive({
  CustomerCode: '',
  CustomerName: '',
  CustomerType: '',
  UserPeople: '',
  Phone: '',
  State: 0,
  Desc: ''
})

// 表单验证规则 - 匹配新的字段名
const rules: FormRules = {
  // CustomerCode: [
  //   { required: true, message: '请输入客户编码', trigger: 'blur' }
  // ],
  CustomerName: [
    { required: true, message: '请输入客户名称', trigger: 'blur' }
  ],
  CustomerType: [
    { required: true, message: '请选择客户类型', trigger: 'change' }
  ],
  UserPeople: [
    { required: true, message: '请输入联系人', trigger: 'blur' }
  ],
  Phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  State: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 搜索表单
const searchForm = reactive({
  CustomerName: '',
  CustomerType: '',
  State: null as number | null
})

// 分页数据
const pagination = reactive({
  pageindex: 1,
  pagesize: 6,
  totalCount: 0,
  totalPage: 0
})

// 获取客户列表数据
const fetchCustomerList = async () => {
  try {
    loading.value = true
    
    const params = {
      pageindex: pagination.pageindex,
      pagesize: pagination.pagesize,
      CustomerName: searchForm.CustomerName || undefined,
      CustomerType: searchForm.CustomerType || undefined,
      State: searchForm.State !== null ? searchForm.State : undefined
    }

    // 移除空值参数
    Object.keys(params).forEach(key => {
      const paramKey = key as keyof typeof params
      if (params[paramKey] === undefined || params[paramKey] === '') {
        delete params[paramKey]
      }
    })

    console.log('API请求参数:', params)
    console.log('使用的客户端:', r3.defaults.baseURL)
    
    const response = await r3.get<ApiResponse>('/sellreadapi/api/Customer/Customerlist', { params })
    
    if (response.data.code === 200) {
      tableData.value = response.data.data.data
      pagination.totalCount = response.data.data.totalCount
      pagination.totalPage = response.data.data.totalPage
      console.log('获取到的数据:', tableData.value)
    } else {
      ElMessage.error(response.data.message || '获取客户列表失败')
    }
  } catch (error: any) {
    console.error('获取客户列表失败:', error)
    ElMessage.error(`网络请求失败: ${error.message}`)
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  pagination.pageindex = 1 // 重置到第一页
  fetchCustomerList()
}

// 重置搜索
const handleReset = () => {
  searchForm.CustomerName = ''
  searchForm.CustomerType = ''
  searchForm.State = null
  pagination.pageindex = 1
  fetchCustomerList()
}

// 分页大小改变
const handleSizeChange = (val: number) => {
  pagination.pagesize = val
  pagination.pageindex = 1
  fetchCustomerList()
}

// 当前页改变
const handleCurrentChange = (val: number) => {
  pagination.pageindex = val
  fetchCustomerList()
}

// 编辑客户
const handleEdit = (row: Customer) => {
  isEdit.value = true
  currentEditId.value = row.id
  dialogVisible.value = true
  
  // 数据反填 - 使用新的字段名
  form.CustomerCode = row.customerCode
  form.CustomerName = row.customerName
  form.CustomerType = row.customerType
  form.UserPeople = row.userPeople
  form.Phone = row.phone
  form.State = row.state
  form.Desc = row.desc
  
  // 清除表单验证
  formRef.value?.clearValidate()
}

// 删除客户
const handleDelete = async (row: Customer) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除客户 "${row.customerName}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用删除API
    const response = await w8.get('/sellwriteapi/api/Customer/CustomerDel', {
      params: {
        Id: row.id
      }
    })
    
    if (response.data.Code === 200) {
      ElMessage.success('删除成功')
      // 刷新列表
      fetchCustomerList()
    } else {
      ElMessage.error(response.data.Message || '删除失败')
    }
  } catch (error: any) {
    if (error.message === 'cancel') {
      ElMessage.info('已取消删除')
    } else {
      ElMessage.error('删除失败，请重试')
      console.error('删除客户失败:', error)
    }
  }
}

// 生成客户编码
const generateCustomerCode = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  const seconds = String(now.getSeconds()).padStart(2, '0')
  
  return `KH${year}${month}${day}${hours}${minutes}${seconds}`
}

// 新增客户
const handleAdd = () => {
  isEdit.value = false
  currentEditId.value = null
  resetForm(false) // 不清空编码
  
  // 自动生成客户编码
  form.CustomerCode = generateCustomerCode()
  console.log('生成的客户编码:', form.CustomerCode)
  
  dialogVisible.value = true
}

// 重置表单
const resetForm = (clearCode = true) => {
  if (clearCode) {
    form.CustomerCode = ''
  }
  form.CustomerName = ''
  form.CustomerType = ''
  form.UserPeople = ''
  form.Phone = ''
  form.State = 0
  form.Desc = ''
  // 清除表单验证
  formRef.value?.clearValidate()
}

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    // 表单验证
    await formRef.value.validate()
    
    submitLoading.value = true
    
    console.log('=== 开始提交客户数据 ===')
    console.log('当前表单数据:', form)
    console.log('是否为编辑模式:', isEdit.value)
    console.log('使用的客户端基础URL:', w8.defaults.baseURL)
    
    let response
    if (isEdit.value) {
      // 编辑模式：调用更新API
      const updateData = {
        id: currentEditId.value,
        ...form
      }
      console.log('编辑客户数据:', updateData)
      response = await w8.post('/sellwriteapi/api/Customer/CustomerUpdate', updateData)
    } else {
      // 新增模式：调用新增API
      console.log('新增客户数据:', form)
      response = await w8.post('/sellwriteapi/api/Customer/CustomerAdd', form)
    }
    
    console.log('API响应:', response.data)
    
    if (response.data.Code === 200) {
      ElMessage.success(isEdit.value ? '客户修改成功' : '客户添加成功')
      dialogVisible.value = false
      resetForm()
      // 刷新列表
      fetchCustomerList()
    } else {
      ElMessage.error(response.data.Message || (isEdit.value ? '修改失败' : '添加失败'))
    }
  } catch (error: any) {
    console.error('提交客户数据失败:', error)
    
    let errorMessage = isEdit.value ? '修改失败' : '添加失败'
    
    if (error.response) {
      const status = error.response.status
      const data = error.response.data
      
      console.error('HTTP错误状态:', status)
      console.error('错误响应数据:', data)
      
      if (status === 400) {
        errorMessage += ': 请求参数错误'
        if (data && data.message) {
          errorMessage += ` - ${data.message}`
        }
      } else if (status === 500) {
        errorMessage += ': 服务器内部错误'
        if (data && data.message) {
          errorMessage += ` - ${data.message}`
        }
      } else {
        errorMessage += `: 服务器错误 (${status})`
        if (data && data.message) {
          errorMessage += ` - ${data.message}`
        }
      }
    } else if (error.request) {
      errorMessage += ': 网络错误，请检查网络连接'
      console.error('网络请求失败:', error.request)
    } else {
      errorMessage += `: ${error.message || '未知错误'}`
    }
    
    ElMessage.error(errorMessage)
  } finally {
    submitLoading.value = false
  }
}

// 导出数据
const handleExport = async () => {
  try {
    exportLoading.value = true
    
    // 获取所有客户数据（不分页）
    const params = {
      pageindex: 1,
      pagesize: 10000, // 获取大量数据
      CustomerName: searchForm.CustomerName || undefined,
      CustomerType: searchForm.CustomerType || undefined,
      State: searchForm.State !== null ? searchForm.State : undefined
    }

    // 移除空值参数
    Object.keys(params).forEach(key => {
      const paramKey = key as keyof typeof params
      if (params[paramKey] === undefined || params[paramKey] === '') {
        delete params[paramKey]
      }
    })

    const response = await r3.get<ApiResponse>('/sellreadapi/api/Customer/Customerlist', { params })
    
    if (response.data.code === 200) {
      const exportData = response.data.data.data
      
      if (exportData.length === 0) {
        ElMessage.warning('没有数据可导出')
        return
      }
      
      // 准备导出数据
      const excelData = exportData.map((item, index) => ({
        '序号': index + 1,
        '客户编码': item.customerCode,
        '客户名称': item.customerName,
        '客户类型': item.customerType,
        '联系人': item.userPeople,
        '联系电话': item.phone,
        '状态': item.state === 0 ? '启用' : '禁用',
        '备注': item.desc || ''
      }))
      
      // 生成Excel文件
      await exportToExcel(excelData, '客户列表')
      
      ElMessage.success(`导出成功，共导出 ${exportData.length} 条数据`)
    } else {
      ElMessage.error(response.data.message || '导出失败')
    }
  } catch (error: any) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败，请重试')
  } finally {
    exportLoading.value = false
  }
}

// 导出到Excel
const exportToExcel = async (data: any[], filename: string) => {
  try {
    // 动态导入xlsx库
    const XLSX = await import('xlsx')
    
    // 创建工作簿
    const wb = XLSX.utils.book_new()
    
    // 创建工作表
    const ws = XLSX.utils.json_to_sheet(data)
    
    // 设置列宽
    const colWidths = [
      { wch: 8 },   // 序号
      { wch: 15 },  // 客户编码
      { wch: 20 },  // 客户名称
      { wch: 12 },  // 客户类型
      { wch: 15 },  // 联系人
      { wch: 15 },  // 联系电话
      { wch: 10 },  // 状态
      { wch: 30 }   // 备注
    ]
    ws['!cols'] = colWidths
    
    // 设置表头样式
    const headerStyle = {
      font: { bold: true, color: { rgb: "FFFFFF" } },
      fill: { fgColor: { rgb: "4472C4" } },
      alignment: { horizontal: "center", vertical: "center" }
    }
    
    // 应用表头样式
    const range = XLSX.utils.decode_range(ws['!ref'] || 'A1')
    for (let col = range.s.c; col <= range.e.c; col++) {
      const cellAddress = XLSX.utils.encode_cell({ r: 0, c: col })
      if (!ws[cellAddress]) ws[cellAddress] = { v: '' }
      ws[cellAddress].s = headerStyle
    }
    
    // 添加工作表到工作簿
    XLSX.utils.book_append_sheet(wb, ws, '客户列表')
    
    // 生成文件名（包含时间戳）
    const now = new Date()
    const timestamp = now.toISOString().slice(0, 19).replace(/[-:T]/g, '')
    const fileName = `${filename}_${timestamp}.xlsx`
    
    // 导出文件
    XLSX.writeFile(wb, fileName)
  } catch (error) {
    console.error('Excel导出失败:', error)
    throw new Error('Excel文件生成失败')
  }
}

// 组件挂载时获取数据
onMounted(() => {
  console.log('组件挂载，开始获取数据...')
  console.log('使用的客户端基础URL:', r3.defaults.baseURL)
  fetchCustomerList()
})
</script>

<style scoped>
.customer-list {
  padding: 0;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 20px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.search-card {
  margin-bottom: 16px;
}

.search-form {
  margin: 0;
}

.action-card {
  margin-bottom: 16px;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 表格样式优化 */
:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 12px 0;
}

/* 按钮样式 */
:deep(.el-button) {
  border-radius: 4px;
}

:deep(.el-button + .el-button) {
  margin-left: 8px;
}

/* 卡片样式 */
:deep(.el-card) {
  border-radius: 8px;
  border: 1px solid #ebeef5;
}

:deep(.el-card__body) {
  padding: 20px;
}

/* 导出按钮样式 */
:deep(.el-button--success) {
  background-color: #67c23a;
  border-color: #67c23a;
}

:deep(.el-button--success:hover) {
  background-color: #85ce61;
  border-color: #85ce61;
}

:deep(.el-button--success:focus) {
  background-color: #67c23a;
  border-color: #67c23a;
}

/* 禁用输入框样式 */
:deep(.el-input.is-disabled .el-input__inner) {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #909399;
  cursor: not-allowed;
}
</style>
